package com.example.nfcschool;

import java.io.FileOutputStream;
import java.io.StringReader;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;

import android.app.ActionBar;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

public class TViewActivity extends Activity {

	TextView irum;
	TextView grade;
	TextView tel;
	TextView birth;
	TextView adds;
	TextView late;
	TextView miss;
	TextView leave;
	
	String telno="";
	SmemberVO premem;
	String cntIn="";
	String cntOut="";
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_tview2);
		
		// ActionBar제거한다.
		ActionBar actionBar = getActionBar();
        actionBar.hide();
		
		Intent i = getIntent();
		telno = i.getStringExtra("tel");
//		Toast.makeText(this, telno, Toast.LENGTH_LONG).show();
		
		 irum = (TextView)findViewById(R.id.irum_text);
		 grade = (TextView)findViewById(R.id.grade_text);
		 tel = (TextView)findViewById(R.id.tel_text);
		 birth = (TextView)findViewById(R.id.birth_text);
		 adds = (TextView)findViewById(R.id.adds_text);
		 late = (TextView)findViewById(R.id.late_text);
		 miss = (TextView)findViewById(R.id.miss_text);
		 leave = (TextView)findViewById(R.id.leave_text);
		 
		

//		 SDBHelper db = new SDBHelper(this, "1myDB", null, 1);
//		 SmemberVO d = db.select(telno);
//			
//		 String[] t = d.getGrade().split("-");
//
//		 irum.setText(d.getIrum());
//		 grade.setText( t[0] + "학년  " + t[1] + "반");
//		 tel.setText( d.getTel() );
//		 birth.setText(d.getBirth());
//		 adds.setText(d.getAdds());
//		 late.setText("지각 : "+d.getLate()+" 회");
//		 miss.setText("결석 : "+d.getMiss()+" 회");
//		 leave.setText("조퇴 : "+d.getLeave()+" 회");
		 
	
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		new SelectOneJsp().execute();
		new AttendCheckJsp().execute();
	}
	
	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
		super.onBackPressed();
		Intent intent = new Intent(this, TListActivity.class).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
		startActivity(intent);
		finish();
	}
	
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}
	
	
	
	public void call(View v){
    	Uri uri = Uri.parse("tel:" + telno);
    	
    	Intent intent = new Intent(Intent.ACTION_CALL, uri);
    	startActivity(intent);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		int id = item.getItemId();
		Intent intent = null;
        switch(id){
        case R.id.LOGOUT : 
        	FileOutputStream fos = null;
    		try{
    			fos = openFileOutput("auto" , Activity.MODE_PRIVATE);
    			String data = "0";         
    			fos.write(data.getBytes());
    			fos.close();
//    			Toast.makeText(this, "파일이 저장되었습니다.", Toast.LENGTH_SHORT).show();
    		}catch(Exception ex){
    			Log.e("파일 save 에러",ex.toString());
    		}
        	finish();
        	intent = new Intent(this, MainActivity.class);
        	startActivity(intent);
        	break;
        }
		return super.onOptionsItemSelected(item);
	}
	
	// Font_Tview
	protected void onStart() {
 		Typeface typeFace = Typeface.createFromAsset(getAssets(), "white.ttf");
 		
 		TextView tv = (TextView)findViewById(R.id.late_text);
 		TextView tv1 = (TextView)findViewById(R.id.miss_text);
 		TextView tv2 = (TextView)findViewById(R.id.leave_text);
        TextView tv3 = (TextView)findViewById(R.id.grade_text);
        TextView tv4 = (TextView)findViewById(R.id.tel_text);
        TextView tv5 = (TextView)findViewById(R.id.birth_text);
        TextView tv6 = (TextView)findViewById(R.id.adds_text);
        TextView tv7 = (TextView)findViewById(R.id.irum_text);
 		
        tv.setTypeface(typeFace);
 		tv1.setTypeface(typeFace);
 		tv2.setTypeface(typeFace);
 		tv3.setTypeface(typeFace);
 		tv4.setTypeface(typeFace);
 		tv5.setTypeface(typeFace);
 		tv6.setTypeface(typeFace);
 		tv7.setTypeface(typeFace);
 		
 		super.onStart();
 	}
	
	
public class SelectOneJsp extends AsyncTask<Void, String, Void> {
		
		String tag="";
		StringBuilder sb=new StringBuilder();
	
		@Override
		protected Void doInBackground(Void... param) {
			
			try {
				try{
				HttpClient client = new DefaultHttpClient();
				String postURL = "http://192.168.10.67:8888/AndroidCheck/SelectOne.jsp";
				HttpPost post = new HttpPost(postURL);

				ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
				
				params.add(new BasicNameValuePair("tel", telno));
				
				UrlEncodedFormEntity ent = new UrlEncodedFormEntity(params,HTTP.UTF_8);
				post.setEntity(ent);
				HttpResponse responsePOST = client.execute(post);
				HttpEntity resEntity = responsePOST.getEntity();
				
				if (resEntity != null) {
//					Log.i("RESPONSE", EntityUtils.toString(resEntity));
					sb.append(EntityUtils.toString(resEntity));
				}
				client.getConnectionManager().shutdown(); //추가된 코드.
				}catch(Exception ex){
					Log.i("TView Select Upload Data",ex.toString());
				}
				
				
				
				// 데이터 받기
				XmlPullParserFactory factory = XmlPullParserFactory.newInstance(); 
	    		factory.setNamespaceAware(true);             
	    		XmlPullParser xpp = factory.newPullParser(); 
	    		xpp.setInput(new StringReader(sb.toString()));   
	    		int eventType = xpp.getEventType();
	    		
	    		
	    		while(eventType != XmlPullParser.END_DOCUMENT){//현재 이벤트 타입이 END_DOCUMENT를 만날때 까지 반복.
	    			
		    		switch(eventType){
	    			case XmlPullParser.START_TAG :  // 이벤트 타입에 START_TAG 라면.
	    				tag = xpp.getName(); // 태그 이름을 추출함.
	    				if(tag.equals("smember")){
	    					premem = new SmemberVO();
	    				}else if(tag.equals("irum")) {
	    					premem.setIrum(xpp.nextText());
	    				}else if(tag.equals("tel")){
	    					premem.setTel(xpp.nextText());
	    				}else if(tag.equals("picture")){
	    					premem.setPicture(xpp.nextText());
	    				}else if(tag.equals("grade")){
	    					premem.setGrade(xpp.nextText());
	    				}else if(tag.equals("pw")){
	    					premem.setPw(1111);
	    				}else if(tag.equals("birth")){
	    					premem.setBirth(xpp.nextText());
	    				}else if(tag.equals("teach")){
	    					premem.setTeach(xpp.nextText());
	    				}else if(tag.equals("adds")){
	    					premem.setAdds(xpp.nextText());
	    				}else if(tag.equals("sno")){
	    					premem.setSno(xpp.nextText());
	    				}
	    			
	    				break;
	    			
	    			}
	    			eventType = xpp.next();
	    		}
				
				
			} catch (Exception e) {
				Log.e("SView Async Err",e.toString());
			}
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			
			Log.e("End of TView", "send?");
			
			String[] splitGrade = premem.getGrade().split("-");
			String year = premem.getBirth().substring(0, 4);
			String month = premem.getBirth().substring(4, 6);
			String day = premem.getBirth().substring(6, 8);

			String first = premem.getTel().substring(0,3);
			String second = premem.getTel().substring(3,7);
			String third = premem.getTel().substring(7, 11);
			
			irum.setText(premem.getIrum());
			grade.setText(splitGrade[0] + " 학년 " + splitGrade[1] + " 반");
			birth.setText(year + "년" + month + "월" + day + "일");
			tel.setText(first+"-"+second+"-"+third);
			adds.setText(premem.getAdds());
			
			super.onPostExecute(result);
		}
	}
	
public class AttendCheckJsp extends AsyncTask<Void, String, Void> {
	
	String tag="";
	StringBuilder sb=new StringBuilder();

	@Override
	protected Void doInBackground(Void... param) {
		
		try {
			
			Log.e("pre","pre");
			
			HttpClient client = new DefaultHttpClient();
			String postURL = "http://192.168.10.67:8888/AndroidCheck/AttendCheck.jsp";
			HttpPost post = new HttpPost(postURL);

			ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
			
			params.add(new BasicNameValuePair("tel", telno));
			
			UrlEncodedFormEntity ent = new UrlEncodedFormEntity(params,HTTP.UTF_8);
			post.setEntity(ent);
			HttpResponse responsePOST = client.execute(post);
			HttpEntity resEntity = responsePOST.getEntity();
			
			if (resEntity != null) {
//				Log.i("RESPONSE", EntityUtils.toString(resEntity));
				sb.append(EntityUtils.toString(resEntity));
			}
			client.getConnectionManager().shutdown(); //추가된 코드.
			
			
			
			
			// 데이터 받기
			XmlPullParserFactory factory = XmlPullParserFactory.newInstance(); 
    		factory.setNamespaceAware(true);             
    		XmlPullParser xpp = factory.newPullParser(); 
    		xpp.setInput(new StringReader(sb.toString()));   
    		int eventType = xpp.getEventType();
    		
    		
    		while(eventType != XmlPullParser.END_DOCUMENT){//현재 이벤트 타입이 END_DOCUMENT를 만날때 까지 반복.
    			
	    		switch(eventType){
    			case XmlPullParser.START_TAG :  // 이벤트 타입에 START_TAG 라면.
    				tag = xpp.getName(); // 태그 이름을 추출함.
    				if(tag.equals("instate")){
    					cntIn = xpp.nextText();
    				}else if(tag.equals("outstate")){
    					cntOut = xpp.nextText();
    				}
    				break;
    			}
    			eventType = xpp.next();
    		}
		} catch (Exception e) {
			Log.e("SView Async Err",e.toString());
		}
		return null;
	}

	@Override
	protected void onPostExecute(Void result) {
		
		Log.e("SView AttendCheck", "end?");
		late.setText("지각 : "+cntIn+"회");
		leave.setText("조퇴 : "+cntOut+"회");
		super.onPostExecute(result);
	}
}
	
	
}
